import 'package:flutter/material.dart';

/// Canvas绘图
class CanvasApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
        home: Scaffold(
          body: Signature(),
        ),
      );
}

class Signature extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SignatureState();
}

class SignatureState extends State<Signature> {
  // 瞄点集合
  List<Offset> _points = <Offset>[];

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // 绘制更新
      onPanUpdate: (DragUpdateDetails details) {
        setState(() {
          // 上下文中获取渲染盒
          RenderBox renderBox = context.findRenderObject();
          // 从渲染盒中进行全局点的一个转换
          Offset localPosition =
              renderBox.globalToLocal(details.globalPosition);
          // 将获取到的点加入绘制点的集合，将点转换为列表
          _points = List.from(_points)..add(localPosition);
        });
      },
      // 绘制结束
      onPanEnd: (DragEndDetails details) => _points.add(null),
      // 普通画笔
      child: CustomPaint(
        // 普通绘画者
        painter: SignaturePainter(_points),
        // 点无穷
        size: Size.infinite,
      ),
    );
  }
}

class SignaturePainter extends CustomPainter {
  final List<Offset> _points;

  SignaturePainter(this._points);

  @override
  void paint(Canvas canvas, Size size) {
    // 初始化画笔
    var paint = Paint()
      ..color = Colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5.0;
    // 绘图
    for (int i = 0; i < this._points.length - 1; i++) {
      if (this._points[i] != null && this._points[i + 1] != null) {
        // 绘制线
        canvas.drawLine(this._points[i], this._points[i + 1], paint);
      }
    }
  }

  // 是否重复绘制
  @override
  bool shouldRepaint(SignaturePainter other) => other._points != this._points;
}
